#include<iostream>
#include<set>
#include<cmath>
using namespace std;

int main()
{
	int n; cin >> n;
	long long ret = 0;
	set<int> mp;
	int num; cin >> num;
	ret += num; mp.insert(num);
	while (--n)
	{
		int x; cin >> x;
		auto it = mp.lower_bound(x);
		int y = (*it);
		if (it != mp.begin())
		{
			int z = (*(--it));
			ret += min(abs(x - y), abs(x - z));
		}
		else
		{
			ret += abs(x - y);
		}
		mp.insert(x);
	}
	cout << ret << endl;
	return 0;
}